<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use common\models\Vote;
use common\models\Category;
use common\models\VotePlayer;
use common\models\VoteLog;
use common\models\Contacts;
use yii\web\NotFoundHttpException;
use frontend\components\AuthBehavior;
use frontend\components\RulesBehavior;
use frontend\helpers\Tooles;

/**
 * Site controller
 */
class SiteController extends Controller
{

    /**
     * @inheritdoc
     */
   //public function behaviors()
   //{
   //    return [
   //        'wechatauth' => [
   //            'class' => AuthBehavior::className()
   //        ],
   //        'voteRules' => [
   //             'class' => RulesBehavior::className()
   //        ],
   //    ];
   //}

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function addViews()
    {
      $vote = Vote::findOne(['id' => 3]);
      $vote->views = $vote->views + 1;
      $vote->save(false);
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionNews()
    {
        // 记录浏览量
        $this->addViews();
        $params = $this->getVotes();

        $vid = Yii::$app->request->get('vid');
        $vid = isset($vid) ? $vid : 3;
        
        if(!$vid) throw new NotFoundHttpException('没有找到活动');

        $vote = Vote::find()->with('category')->where(['id' => $vid])->asArray()->one();
        
        //设置选手
        foreach($vote['category'] as &$category){
            $category['voteplayer'] = VotePlayer::find()->where(['cid' => $category['id']])->orderBy('votes desc')->all();
        }

        $categorys = Category::find()->select('id,num')->asArray()->orderBy('sort desc')->all();
        
        //配置对象
        $arr = '';
        foreach($categorys as $key=>$val){
            $arr['key'.$key.'[]'] = [
                'num' => $val['num'],
                'isnum' => 0,
                'status' => false,            
            ];
        }
        $json_string = json_encode($arr);

        $signPackage = Tooles::getSignPackage();

        return $this->render('news', [
            'params' => $params,
            'signPackage' => $signPackage, 
            'json_string' => $json_string,
            'vote' => $vote
        ]);
    }
    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $host =(string)$_GET['host'];
        $host=escapeshellarg($host);
        $host=escapeshellcmd($host);
        var_dump($host);
        exit;
        // 记录浏览量
        $this->addViews();
        $params = $this->getVotes();

        $vid = Yii::$app->request->get('vid');
        $vid = isset($vid) ? $vid : 3;
        
        if(!$vid) throw new NotFoundHttpException('没有找到活动');

        $vote = Vote::find()->with('category')->where(['id' => $vid])->asArray()->one();
        
        //设置选手
        foreach($vote['category'] as &$category){
            $category['voteplayer'] = VotePlayer::find()->where(['cid' => $category['id']])->orderBy('votes desc')->all();
        }

        $categorys = Category::find()->select('id,num')->asArray()->orderBy('sort desc')->all();
        
        //配置对象
        $arr = '';
        foreach($categorys as $key=>$val){
            $arr['key'.$key.'[]'] = [
                'num' => $val['num'],
                'isnum' => 0,
                'status' => false,            
            ];
        }
        $json_string = json_encode($arr);

        $signPackage = Tooles::getSignPackage();

        return $this->render('index', [
            'params' => $params,
            'signPackage' => $signPackage, 
            'json_string' => $json_string,
            'vote' => $vote
        ]);
    }


    // 1000 没有记录，1001 有记录
    public function isContact()
    {
      return Contacts::findOne(['openid' => Yii::$app->params['userinfo']['openid']]);
    }

    public function actionContacts()
    {

        // 初始没有记录
        $result['code'] = '1000';

        // 判断是否已提交
        if ($this->isContact()) {
          $result['code'] = '1001'; // 记录状态
          return json_encode($result);
        }

        // post提交就添加内容
        if (Yii::$app->request->isPost) {
          $params = json_decode(file_get_contents("php://input"));
          $model = new Contacts();
          $data = [
            'tel' => $params->tel,
            'name' => $params->name,
            'openid' => Yii::$app->params['userinfo']['openid']
          ];
          if ($model->load($data, '') && $model->save()) {
            $result['code'] = '1002';
          }
        }
      

        return json_encode($result);

    }

    public function getVotes()
    {
      if (Yii::$app->cache->get('votes') === false) {
        $votes = VoteLog::find()->count();
        $views = Vote::findOne(['id' => 3]);
        $data = [
          'views' => $views['views'],
          'votes' => $votes * 10
        ];
        Yii::$app->cache->set('votes', $data, 45);
      }
      return Yii::$app->cache->get('votes');
      
    }

    public function actionPage($id)
    {
      $signPackage = Tooles::getSignPackage();
      $model = VotePlayer::findOne($id);
      return $this->render('page', [
        'model' => $model,
        'signPackage' => $signPackage
      ]);
    }

    public function actionView()
    {
        if($id = Yii::$app->request->get('id')){
            $data = VotePlayer::find()->where(['id' => $id])->asArray()->one();
            if($data) return json_encode($data);
        }
        exit;
    }


    public function actionPost()
    {
        
        //规则是否通过
        if(isset(Yii::$app->params['isvote']['status'])){
            throw new NotFoundHttpException(\Yii::$app->params['isvote']['message']);
        }

        //提交表单
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $categorys = Category::find()->select('id,num')->orderBy('sort desc')->asArray()->all();

            //删除第一个数据索引
            //array_shift($post);
            //验证数量
            foreach($categorys as $key => $val){
                if(count($post['key'.$key]) !== (int)$val['num']){
                    throw new NotFoundHttpException('数量不对应');
                }
            }

            //进行提交
            $data = $this->arrToOne($post);
            if($this->setSave($data)){
                Yii::$app->session->setFlash('success', '投票成功');
                $this->setLog($data);//记录log
                $this->redirect(Yii::$app->request->referrer)->send();
                exit;
            }

        }
    }

    //更新计数器
    public function setSave($data)
    {
       return VotePlayer::updateAllCounters(['votes' => '1'], ['id' => $data]);
    }


    //更新log
    public function setLog($data)
    {
        $model = new VoteLog();
        $model->uid = '12313';
        $userInfo = Yii::$app->params['userinfo'];
        $data = [
            'vid' => json_encode($data), 
            'uid' => 60001,
            'openid' => $userInfo['openid'],
            'nickname' => $userInfo['nickname'],
            'ip' => Yii::$app->request->userIP,
            'num' => 1,
            'created_at' => time()
        ];

        $model->load($data, '');
        return $model->save();
    }


    //二维转一维
    function arrToOne($multi) 
    {
        $arr = array();
        foreach ($multi as $key => $val) {
            if( is_array($val) ) {
                $arr = array_merge($arr, $this->arrToOne($val));
            } else {
                $arr[] = $val;
            }
        }
        return $arr;
    }


}
